import PopupConstructor from "./popup.vue"
import { createApp } from "vue";
import store from '@/store'

const randomString = ( length=64 ) => {
  let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  let result = '';
  for (let i = length; i > 0; --i) 
    result += str[Math.floor(Math.random() * str.length)];
  return result;
}

const ModalBox = (options = {} ) => {
  const root = document.createElement('div')
  document.body.appendChild(root)
  const app = createApp(PopupConstructor, {
    ...options, modelValue: true, remove: true,
    removed: ()=>{
        app.unmount(root)
        document.body.removeChild(root)
    }
  })
  app.provide('v3popup', V3Popup)
  app.component('v3-popup', PopupConstructor)
  return app.use(store).mount(root)
}

const V3Popup = (options = {}) => {
  options.id = options.id || 'v3popup_'+randomString(8)
  return ModalBox(options)
}

V3Popup.install = app => {
  app.component('v3-popup', PopupConstructor)
  // app.config.globalProperties.$v3popup = V3Popup
  app.provide('v3popup', V3Popup)
}

export default V3Popup
